using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using GameEditor.Common;
namespace GameEditor.Common
{
    public partial class Slider : UserControl
    {

        public Slider()
        {
            InitializeComponent();
        }
        private Range<float>? range;

        public Range<float>? Range
        {
            get { return range; }
            set { range = value; }
        }
        private ITypeDescriptorContext context;

        public ITypeDescriptorContext Context
        {
            get { return context; }
            set { context = value; }
        }
        private Type targetType = typeof(float);

        public Type TargetType
        {
            get { return targetType; }
            set { targetType = value; }
        }


        public float Value
        {
            get
            {
                float value = 1.0f * trackBar1.Value;
                if (range != null)
                {
                    //value = value * (range.Value.Maximum - range.Value.Minimum) / (trackBar1.Maximum - trackBar1.Minimum) + range.Value.Minimum;
                    value = MathHelper.IntervalMap(value, new Range<float>(trackBar1.Maximum, trackBar1.Minimum), new Range<float>(range.Value.Minimum, range.Value.Maximum));
                }
                return value;
            }
            set 
            {
                //from range to trackbars range
                float v = value;
                if (range != null)
                {
                    v = MathHelper.IntervalMap(v, new Range<float>(range.Value.Minimum, range.Value.Maximum), new Range<float>(trackBar1.Maximum, trackBar1.Minimum));
                }
                trackBar1.Value = (int)v;
                
            }
        }


        private void trackBar1_ValueChanged(object sender, EventArgs e)
        {
            if (context != null)
            {
                if (targetType == typeof(float))
                    context.PropertyDescriptor.SetValue(context.Instance, Value);
                else if (targetType == typeof(int))
                    context.PropertyDescriptor.SetValue(context.Instance, (int)Value);
                else
                    context.PropertyDescriptor.SetValue(context.Instance, Convert.ChangeType(Value, targetType));
            }
        }


        
    }
}
